//
//  AudioPlayerController.m
//  AudioPlayer
//
//  Created by ClaudeLi on 16/4/1.
//  Copyright © 2016年 ClaudeLi. All rights reserved.
//

#import "AudioPlayerController.h"
#import "AudioPlayerController+methods.h"
#import "NSString+time.h"
#import "JrdCommon.h"
#import "LCCSqliteManager.h"
#import "JrdDatamanager.h"
#import "CKHttpCommunicate.h"
@interface AudioPlayerController ()<UIGestureRecognizerDelegate,UIWebViewDelegate, UIGestureRecognizerDelegate>{
    AVPlayerItem *playerItem;
    id _playTimeObserver; // 播放进度观察者
    NSArray *_modelArray; // 歌曲数组
    NSArray *_randomArray; //随机数组
    NSInteger _index; // 播放标记
    BOOL isPlaying; // 播放状态
    BOOL isRemoveNot; // 是否移除通知
    AudioPlayerMode _playerMode; // 播放模式

    MusicModel *_playingModel; // 正在播放的model
    CGFloat _totalTime; // 总时间
    
    float current_time;
    LCCSqliteManager* manager;
    UIWebView* myWebView;
    int g_scale;
    BOOL v_first_enter;
}
@property (weak, nonatomic) IBOutlet UISlider *paceSlider; // 进度条
@property (weak, nonatomic) IBOutlet UIButton *playButton; // 播放按钮
@property (weak, nonatomic) IBOutlet UILabel *titleLabel; // 歌名Label
@property (weak, nonatomic) IBOutlet UILabel *singerLabel; // 歌手Label
@property (weak, nonatomic) IBOutlet UILabel *playingTime; // 当前播放时间Label
@property (weak, nonatomic) IBOutlet UILabel *maxTime; // 总时间Label
@property (weak, nonatomic) IBOutlet UIButton *modeButton; // 播放模式按钮
@property (nonatomic, strong) AVPlayer *player;
@property (strong, nonatomic) IBOutlet UIView *backView;
@property (strong, nonatomic) IBOutlet UIButton *downLoadIcon;
@end

static AudioPlayerController *audioVC;
@implementation AudioPlayerController

+(AudioPlayerController *)audioPlayerController{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioVC = [[AudioPlayerController alloc] init];
        audioVC.view.backgroundColor = [UIColor whiteColor];
        audioVC.player = [[AVPlayer alloc]init];
    });
    return audioVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.paceSlider setThumbImage:[UIImage imageNamed:@"Slider_控制点"] forState:UIControlStateNormal];
    [self.paceSlider addTarget:self action:@selector(changeSlider:) forControlEvents:UIControlEventTouchDown];
    [self.paceSlider addTarget:self action:@selector(touchSlide) forControlEvents:UIControlEventTouchUpInside];
    [self.paceSlider addTarget:self action:@selector(toudhDownSlide) forControlEvents:UIControlEventTouchDown];
    self.downLoadIcon.hidden = YES;
    
    UITapGestureRecognizer *_tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTapGesture:)];
    _tapGesture.delegate = self;
    [self.paceSlider addGestureRecognizer:_tapGesture];
    manager = [LCCSqliteManager shareInstance];
}

- (void)actionTapGesture:(UITapGestureRecognizer *)sender{
    CGPoint touchPoint = [sender locationInView:self.paceSlider];
    CGFloat value = (self.paceSlider.maximumValue - self.paceSlider.minimumValue) * (touchPoint.x / self.paceSlider.frame.size.width );
    [self.paceSlider setValue:value animated:YES];
    CMTime dragedCMTime = CMTimeMake(self.paceSlider.value, 1);
    [playerItem seekToTime:dragedCMTime];
}

- (void)appHasGoneInbackground{
    [[NSUserDefaults standardUserDefaults] setFloat:current_time forKey:@"current_time"];
    [self stop];
}
- (void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appHasGoneInbackground)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];

}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    [self setRotatingViewFrame];
}

- (void)initWithArray:(NSArray *)array index:(NSInteger)index{
    _index = index;
    _modelArray = array;
    v_first_enter = true;
    _randomArray = nil;
    current_time = [[NSUserDefaults standardUserDefaults] floatForKey:@"current_time"];
    [self updateAudioPlayer];
}

- (void)updateAudioPlayer{

    if (isRemoveNot) {
        // 如果已经存在 移除通知、KVO，各控件设初始值
        [self removeObserverAndNotification];
        [self initialControls];
        isRemoveNot = NO;
    }
    MusicModel *model;
        // 判断是不是随机播放
        if (_playerMode == AudioPlayerModeRandomPlay) {
            // 如果是随机播放，判断随机数组是否有值
            if (_randomArray.count == 0) {
                // 如果随机数组没有值，播放当前音乐并给随机数组赋值
                model = [_modelArray objectAtIndex:_index];
                _randomArray = [_modelArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2) {
                    return arc4random() % _modelArray.count;
                }];
            }else{
                // 如果随机数组有值，从随机数组取值
                model = [_randomArray objectAtIndex:_index];
            }
        }else{
            model = [_modelArray objectAtIndex:_index];
        }
        _playingModel = model;
        // 更新界面歌曲信息：歌名，歌手，图片
        [self updateUIDataWith:model];
    //}else{
        /*zlwu添加： 播放本地音频*/
        NSURL *url = nil;//[NSURL fileURLWithPath:filePath];
        NSString* audio_name = nil;
        if(nil != model.localPath){
            NSInteger index = [model.localPath rangeOfString:@"&"].location;
            audio_name = [model.localPath substringToIndex:index];
            //NSString* doc_name = [audio_name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            url =[NSURL fileURLWithPath:audio_name];
        }

        if(nil == url){
            NSString* audio_name = [model.fileName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:audio_name]];
        }else{
            playerItem = [AVPlayerItem playerItemWithURL:url];
        }
        NSString * searchCondition = [NSString stringWithFormat:@"node_id=%@ and user_id=%@",
                                  model.music_id, [JrdDatamanager manager].user.userId];
        NSArray* array = [manager searchDataFromSheet:@"nodelist" where:searchCondition];
        if(nil != array && 0 != array.count){
            current_time = [[NSString stringWithFormat:@"%@",array[0][NODE_STUDY_TIME]] floatValue];
        }
    
        //get play time accord to datebase recorder
        CMTime dragedCMTime = CMTimeMake(current_time, 1);
        [playerItem seekToTime:dragedCMTime];
    [self updateVideoSlider:dragedCMTime.value/dragedCMTime.timescale];
        [self.player replaceCurrentItemWithPlayerItem:playerItem];
        [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
        [self monitoringPlayback:playerItem];// 监听播放状态
        [self addEndTimeNotification];
        isRemoveNot = YES;
        [self createwebView_Ext];

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        [self createWebView];
    });



    
}

// 各控件设初始值
- (void)initialControls{
    [self stop_ext];
    self.playingTime.text = @"00:00";
    self.paceSlider.value = 0.0f;
    [self.rotatingView removeAnimation];
}

- (void)updateUIDataWith:(MusicModel *)model{
    self.titleLabel.text = model.name;
    self.singerLabel.text = model.singer;
    [self setImageWith:model];
}

#pragma mark - KVO - status
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *item = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            
            CMTime duration = item.duration;// 获取视频总长度
            [self setMaxDuratuin:CMTimeGetSeconds(duration)];
            if(false == v_first_enter)
                [self play];
            else
                v_first_enter = false;
        }else if([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
            [self stop];
        }
    }
}

- (void)setMaxDuratuin:(float)duration{
    _totalTime = duration;
    self.paceSlider.maximumValue = duration;
    self.maxTime.text = [NSString convertTime:duration];
}

#pragma mark - _playTimeObserver
- (void)monitoringPlayback:(AVPlayerItem *)item {
    WS(ws);
    //这里设置每秒执行30次
    _playTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 30) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 计算当前在第几秒
        NSLog(@"zlwu add monitor");
        float currentPlayTime = (double)item.currentTime.value/item.currentTime.timescale;
        current_time = currentPlayTime;
        [ws updateVideoSlider:currentPlayTime];
    }];
}

- (void)updateVideoSlider:(float)currentTime{
    [self setLockViewWith:_playingModel currentTime:currentTime];
    self.paceSlider.value = currentTime;
    self.playingTime.text = [NSString convertTime:currentTime];
}
- (void)toudhDownSlide{
    [self.player removeTimeObserver:_playTimeObserver];
    _playTimeObserver = nil;
}

- (void)touchSlide{
    //NSLog(@"zlwu add for touchSlide");
    CMTime dragedCMTime = CMTimeMake(self.paceSlider.value, 1);
    [playerItem seekToTime:dragedCMTime];
    [self updateVideoSlider:dragedCMTime.value/dragedCMTime.timescale];
    [self monitoringPlayback:playerItem];// 监听播放状态
}
- (IBAction)changeSlider:(id)sender{
    NSLog(@"zlwu add for changeSlider, slide value = %f",self.paceSlider.value);
    //转换成CMTime才能给player来控制播放进度
    CMTime dragedCMTime = CMTimeMake(self.paceSlider.value, 1);
    //[playerItem seekToTime:dragedCMTime];
    
    [self updateVideoSlider:dragedCMTime.value/dragedCMTime.timescale];
}

-(void)addEndTimeNotification{
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

-(void)playbackFinished:(NSNotification *)notification{
    NSLog(@"视频播放完成.");
    if (_playerMode == AudioPlayerModeSinglePlay) {
        playerItem = [notification object];
        [playerItem seekToTime:kCMTimeZero];
        [self.player play];
    }else{
        [self nextIndexAdd];
        [self updateAudioPlayer];
    }
}

#pragma mark --按钮点击事件--
- (IBAction)disMissSelfClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kReloadDataNotification object:self];
    }];
}
- (IBAction)playAndPauseClick:(id)sender {
    [self playerStatus];
}

- (void)playerStatus{
    if (isPlaying) {
        [self stop];
    }else{
        [self play];
    }
}

- (IBAction)previousClick:(id)sender {
    NSString * searchCondition = [NSString stringWithFormat:@"node_id=%@ and user_id=%@",
                                  _playingModel.music_id,[JrdDatamanager manager].user.userId];
    
    Boolean ret = [manager updateDataToSheet_StudyTime:@"nodelist" withData:@[[NSString stringWithFormat:@"%f",self.paceSlider.value], [NSString stringWithFormat:@"%f",self.paceSlider.maximumValue]] where:searchCondition];
    NSLog(@"ret = %d", ret);
    [self inASong];
}

- (void)inASong{
    if (_playerMode != AudioPlayerModeSinglePlay) {
        [self previousIndexSub];
    }
    [self updateAudioPlayer];
}

- (IBAction)nextClick:(id)sender {
    NSString * searchCondition = [NSString stringWithFormat:@"node_id=%@ and user_id=%@",
                                  _playingModel.music_id,[JrdDatamanager manager].user.userId];
    
    Boolean ret = [manager updateDataToSheet_StudyTime:@"nodelist" withData:@[[NSString stringWithFormat:@"%f",self.paceSlider.value], [NSString stringWithFormat:@"%f",self.paceSlider.maximumValue]] where:searchCondition];
    NSLog(@"ret = %d", ret);
    [self theNextSong];
}

- (void)theNextSong{
    if (_playerMode != AudioPlayerModeSinglePlay) {
        [self nextIndexAdd];
    }
    [self updateAudioPlayer];
}

- (void)nextIndexAdd{
    _index++;
    NSLog(@"zlwu add for next IndexAdd, index = %ld", (long)_index);
    if (_index == _modelArray.count) {
        _index = 0;
    }
    MusicModel *model = [_modelArray objectAtIndex:_index];
    if(0 == [model.singer intValue]){
        [self nextIndexAdd];
    }
}

- (void)previousIndexSub{
    _index--;
    if (_index < 0) {
        _index = _modelArray.count -1;
    }
    MusicModel *model = [_modelArray objectAtIndex:_index];
    if(0 == [model.singer intValue]){
        [self previousIndexSub];
    }

}

- (IBAction)clickPlayerMode:(id)sender {
    switch (_playerMode) {
        case AudioPlayerModeOrderPlay:{
                _playerMode = AudioPlayerModeRandomPlay;
                [_modeButton setImage:[UIImage imageNamed:@"MusicPlayer_随机播放"] forState:UIControlStateNormal];
                [self progressHUDWith:@"随机播放"];
                _randomArray = [_modelArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2) {
                    return arc4random() % _modelArray.count;
                }];
            }break;
        case AudioPlayerModeRandomPlay:
            _playerMode = AudioPlayerModeSinglePlay;
            [_modeButton setImage:[UIImage imageNamed:@"MusicPlayer_单曲循环"] forState:UIControlStateNormal];
            [self progressHUDWith:@"单曲循环"];
            break;
        case AudioPlayerModeSinglePlay:
            _playerMode = AudioPlayerModeOrderPlay;
            [_modeButton setImage:[UIImage imageNamed:@"MusicPlayer_顺序播放"] forState:UIControlStateNormal];
            [self progressHUDWith:@"顺序播放"];
            break;
        default:
            break;
    }
}

- (void)play{
    isPlaying = YES;
    [self.player play];
    [self.playButton setImage:[UIImage imageNamed:@"btn-pause-normal"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"btn-pause-press"] forState:UIControlStateHighlighted];

    // 开始旋转
    [self.rotatingView resumeLayer];
}

- (void)stop{
    isPlaying = NO;
    [self.player pause];
    [self.playButton setImage:[UIImage imageNamed:@"btn-play-normal"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"btn-play-press"] forState:UIControlStateHighlighted];

    // 停止旋转
    [self.rotatingView pauseLayer];
    //if 0 is the paceslider.value, not update
    if(0 == self.paceSlider.value){
        return;
    }

    NSString * searchCondition = [NSString stringWithFormat:@"node_id=%@ and user_id=%@",
                                  _playingModel.music_id,[JrdDatamanager manager].user.userId];
    
    Boolean ret = [manager updateDataToSheet_StudyTime:@"nodelist" withData:@[[NSString stringWithFormat:@"%f",self.paceSlider.value], [NSString stringWithFormat:@"%f",self.paceSlider.maximumValue]] where:searchCondition];
    NSLog(@"ret = %d", ret);
    //upload user study info to cloud;
    NSString* course_id= [NSString stringWithFormat:@"%@", _playingModel.course_id];
    NSDictionary *parameter = @{
                                @"userid":[JrdDatamanager manager].user.userId,
                                @"courseid":course_id,
                                @"learntime":[NSString stringWithFormat:@"%f",self.paceSlider.value]
                                };
    
    [CKHttpCommunicate createRequest:HTTP_UPLOAD_STUDY_INFO WithParam:parameter withMethod:POST success:^(id result) {
        if (result) {
            NSLog(@"result:%@",result);
        }
    } failure:^(NSError *erro) {
        NSLog(@"failure");
        
    } showHUD:self.view];}

- (void)stop_ext{
    isPlaying = NO;
    [self.player pause];
    [self.playButton setImage:[UIImage imageNamed:@"btn-play-normal"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"btn-play-press"] forState:UIControlStateHighlighted];

    // 停止旋转
    [self.rotatingView pauseLayer];
}
- (IBAction)downloadAction:(id)sender {
    NSLog(@"点击下载");
}
- (IBAction)rightButtonAction:(id)sender {
    NSLog(@"分享");
}

#pragma mark - 移除通知&KVO
- (void)removeObserverAndNotification{
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [playerItem removeObserver:self forKeyPath:@"status"];
    [self.player removeTimeObserver:_playTimeObserver];
    _playTimeObserver = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

#pragma mark - 后台UI设置
- (void)setLockViewWith:(MusicModel*)model currentTime:(CGFloat)currentTime
{
    NSMutableDictionary *musicInfo = [NSMutableDictionary dictionary];
    // 设置Singer
    //[musicInfo setObject:model.singer forKey:MPMediaItemPropertyArtist];
    // 设置歌曲名
    //[musicInfo setObject:model.name forKey:MPMediaItemPropertyTitle];
    // 设置封面
    // zlwu 修改
    /*MPMediaItemArtwork *artwork;
    artwork = [[MPMediaItemArtwork alloc] initWithImage:self.rotatingView.imageView.image];
    [musicInfo setObject:artwork forKey:MPMediaItemPropertyArtwork];*/
    //音乐剩余时长
    [musicInfo setObject:[NSNumber numberWithDouble:_totalTime] forKey:MPMediaItemPropertyPlaybackDuration];
    //音乐当前播放时间
    [musicInfo setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:musicInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //webView.gapBetweenPages=10;
    /*CGSize contentSize = webView.scrollView.contentSize;
    CGSize viewSize = self.view.bounds.size;
    
    float rw = viewSize.width / contentSize.width;
    
    webView.scrollView.minimumZoomScale = rw;
    webView.scrollView.maximumZoomScale = rw;
    webView.scrollView.zoomScale = rw;*/
    //[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '250%'"];
    NSLog(@"%f",webView.pageLength);
    NSLog(@"%f",webView.gapBetweenPages);
    NSLog(@"%zi",webView.pageCount);
    NSLog(@"%@",webView.request);
}

- (void)createwebView_Ext{
    myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 20 - 70- 16)];
    
    myWebView.delegate=self;
    myWebView.scalesPageToFit=YES;
    [self.backView addSubview:myWebView];

}

- (void)createWebView{
    MusicModel* model;
    if (_playerMode == AudioPlayerModeRandomPlay) {
        // 如果是随机播放，判断随机数组是否有值
        if (_randomArray.count == 0) {
            // 如果随机数组没有值，播放当前音乐并给随机数组赋值
            model = [_modelArray objectAtIndex:_index];
            _randomArray = [_modelArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2) {
                return arc4random() % _modelArray.count;
            }];
        }else{
            // 如果随机数组有值，从随机数组取值
            model = [_randomArray objectAtIndex:_index];
        }
    }else{
        model = [_modelArray objectAtIndex:_index];
    }
    _playingModel = model;
    NSString* doc_name ;
    NSData *data;
    NSURL* url;
    /*if([model.docName containsString:@"html"]){
        doc_name= [[NS	Bundle mainBundle] pathForResource:@"Course_des" ofType:@"pdf"];
    }else{*/
    if(nil != model.localPath){
        NSInteger index = [model.localPath rangeOfString:@"&"].location;
        NSString* web_name = [model.localPath substringFromIndex:(index +1)];
        doc_name=[web_name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        data = [NSData dataWithContentsOfFile:web_name];
        if(nil == data)
        {
            doc_name=[model.docName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            url=[NSURL URLWithString:doc_name]; //-->远程
            // load web doc
            data = [[NSData alloc] initWithContentsOfURL:url];
        }
    }else{
        doc_name=[model.docName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        url=[NSURL URLWithString:doc_name]; //-->远程
        // load web doc
        data = [[NSData alloc] initWithContentsOfURL:url];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if([doc_name containsString:@"htm"] ||[doc_name containsString:@"html"]){
            [myWebView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:url];
        }else if([doc_name containsString:@"pdf"] ||[doc_name containsString:@"pdf"]){
            [myWebView loadData:data MIMEType:@"text/pdf" textEncodingName:@"UTF-8" baseURL:url];
        }else{
            [myWebView loadData:data MIMEType:@"text/doc" textEncodingName:@"UTF-8" baseURL:url];
        }
    });
    
    UIPinchGestureRecognizer *pinch =
    [[UIPinchGestureRecognizer alloc]
     initWithTarget:self
     action:@selector(pinching:)];
    
    pinch.delegate = self;
    
    [myWebView addGestureRecognizer:pinch];
    
    [myWebView setUserInteractionEnabled:YES];
    [myWebView setMultipleTouchEnabled:YES];
}

-(void) pinching: (UIPinchGestureRecognizer *) sender {
    
    int scale = 100*sender.scale;
    if(100 == scale){
        NSLog(@"sender.scale = %d", scale);
    }
    NSString* string = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",scale];
    [myWebView stringByEvaluatingJavaScriptFromString:string];
}

- (void)viewWillDisappear:(BOOL)animated{
    [self stop];
    //[[NSUserDefaults standardUserDefaults] setFloat:current_time forKey:@"current_time"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidDisappear:(BOOL)animated{
    //[[NSUserDefaults standardUserDefaults] setFloat:current_time forKey:@"current_time"];
    //[self stop];
    [self removeObserverAndNotification];
    [self initialControls];
    isRemoveNot = NO;
    //[playerItem removeObserver:self forKeyPath:@"status"];
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    NSLog(@"webViewDidStartLoad");
    
}


-(void)webView:(UIWebView*)webView  DidFailLoadWithError:(NSError*)error{
    
    NSLog(@"DidFailLoadWithError");
    
}


- (IBAction)back:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
